/*
 * SPDX-License-Identifier:	GPL-2.0+
 */
#include <common.h>
#include <watchdog.h>
#include <asm/io.h>
#include <asm/utils.h>
#include <asm/arch/hardware.h>

#define DW_WDT_CR    0x00
#define DW_WDT_TORR  0x04
#define DW_WDT_CRR   0x0C

#define DW_WDT_CR_EN_OFFSET     0x00
#define DW_WDT_CR_RMOD_OFFSET   0x01
#define DW_WDT_CR_RMOD_VAL      0x00
#define DW_WDT_CRR_RESTART_VAL  0x76

#define WDT_DEFAULT_CLOCK       (1000000)

/*
 * Set the watchdog time interval.
 * Counter is 32 bit.
 */
static int fh_wdt_settimeout(unsigned int timeout)
{
	int i;

	/* calculate the timeout range value */
	i = (log_2_n_round_up(timeout * WDT_DEFAULT_CLOCK)) - 16;

	if (i > 15)
		i = 15;
	if (i < 0)
		i = 0;

	SET_REG(WDT_REG_BASE + DW_WDT_TORR, i);
	return 0;
}

static int fh_wdt_settimeoutmax(void)
{
	SET_REG(WDT_REG_BASE + DW_WDT_TORR, 15);
	return 0;
}

static void fh_wdt_enable(void)
{
	SET_REG(WDT_REG_BASE + DW_WDT_CR,
		(DW_WDT_CR_RMOD_VAL << DW_WDT_CR_RMOD_OFFSET) |
		(0x1 << DW_WDT_CR_EN_OFFSET));
}

static unsigned int fh_wdt_is_enabled(void)
{
	unsigned int val;

	val = GET_REG(WDT_REG_BASE + DW_WDT_CR);
	return (val & 0x1);
}

#if defined(CONFIG_HW_WATCHDOG)
void hw_watchdog_reset(void)
{
	if (fh_wdt_is_enabled())
		/* restart the watchdog counter */
		SET_REG(WDT_REG_BASE + DW_WDT_CRR,
				DW_WDT_CRR_RESTART_VAL);
}

void hw_watchdog_init(void)
{
	/* reset to disable the watchdog */
	hw_watchdog_reset();
	/* set timer in max */
	fh_wdt_settimeoutmax();
	/* enable the watchdog */
	fh_wdt_enable();
	/* reset the watchdog */
	hw_watchdog_reset();
}

void hw_watchdog_settimeout(unsigned int timeout)
{
	fh_wdt_settimeout(timeout);
}

#endif
